from mongoengine import Document, StringField, IntField, DateTimeField
from datetime import datetime

class User(Document):
    # 假设 openid 是唯一的
    openid = StringField(required=True, unique=True)
    nickname = StringField(required=True, max_length=50)
    level = IntField(min_value=1)
    score = IntField(default=0)
    created_at = DateTimeField(default=datetime.now)
    updated_at = DateTimeField(default=datetime.now)
    
    
    def save(self, *args, **kwargs):
        if not self.updated_at:  # 如果 updated_at 没有设置，则设置为创建时间
            self.updated_at = datetime.now()
        else:  # 否则更新为当前时间
            self.updated_at = datetime.now()
        super(User, self).save(*args, **kwargs)
        
    # 可以添加方法来表示业务逻辑，例如获取用户信息
    def get_user_info(self):
        return {
            "openid": self.openid,
            "nickname": self.nickname,
            "level": self.level,
            "score": self.score,
            "created_at": self.created_at.isoformat(),
            "updated_at": self.updated_at.isoformat(),
        }